package com.hsmpay.utils

import com.hsmpay.yl8583.utils.TestDes.hexStringToByte
import com.hsmpay.yl8583.utils.TestDes.XORContent
import com.hsmpay.yl8583.utils.TestDes.byte2hex
import com.hsmpay.utils.DesUtil;


fun makePin(pan: String, pin: String, encryptedPinKey: String, masterKey: String): String {
    var pinKey = DesUtil.decode3DES(encryptedPinKey, masterKey)
    pan.substring(pan.length - 13, pan.length - 1)
    var temp = "%16s".format(pan.substring(pan.length - 13, pan.length - 1)).replace(' ', '0')

    "%-16s".format("%2s".format(pin.length) + pin).replace(' ', '0')
    var res = XORContent(hexStringToByte(pin), hexStringToByte(pan))

//    var res1 = DesUtil.compute3DES()
    return ""
}

fun getPin(pinBlock: String, pan: String, encryptedPinKey: String, masterKey: String): String {
    var pinKey = encryptedPinKey
    if (masterKey.isNotEmpty())
        pinKey = DesUtil.decode3DES(encryptedPinKey, masterKey)
    var res = DesUtil.decode3DES(hexStringToByte(pinBlock), hexStringToByte(pinKey))
    println(byte2hex(res))

    pan.substring(pan.length - 13, pan.length - 1)
    var temp = "%16s".format(pan.substring(pan.length - 13, pan.length - 1)).replace(' ', '0')

    var tempPin = byte2hex(XORContent(res, hexStringToByte(temp)))

    return tempPin.substring(2, tempPin.indexOf('F'))
}

fun main(args: Array<String>) {
    val pinBlock = "F685312539FBFE5F"
    val pan = "6210676802072012686"
    val masterKey = "6D71BCE56668640C29D8092B2B46D7F1"
//    val encryptedPinKey = DesUtil.encrypt3DES("470840710C3830261C623C1A2348B000", masterKey)
    val encryptedPinKey = "470840710C3830261C623C1A2348B000"

    println(getPin(pinBlock, pan, encryptedPinKey, ""))
}
